import axios from "axios";
import store from "@/store";
import { setToken } from "@/utils/storage";
import { ElColorPicker, ElMessage } from "element-plus";
import router from "@/router";

const request = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    // baseURL: '192.168.123.170:10003',
    timeout: 5000
})
request.interceptors.request.use((config) => {
    const { token } = store.state
    // config.header = config.method =='GET' || config.method == 'DELETE' ? {'content-type':'application/x-www-form-urlencoded'} : 
    // {'content-type':'application/json'}
    if (token) {
        config.headers.token = token
    }
    return config;
})
request.interceptors.response.use((response) => {
    const { config, data } = response
    if(data.code === '200') {
        return data.data
    } else if (config?.responseType === 'blob') {
        const fileName = config.headers['x-real-name']
        return { [fileName]:data }
    } else if (data.code === '401' || data.message === '请求未携带token，无权限访问') {
        setToken({})
        store.state.token = null
        router.push('/login')
    }
    ElMessage({
        message: data.msg,
        type: "warning"
    })
    return Promise.reject(new ElColorPicker(data.msg))
},(err) => {
    ElMessage.warning('服务器出错稍后重试')
    return Promise.reject(err)
})

export default request